<template>
  <a-card title="计算公式： 定价 = (售价 + 优惠券) / 折扣率" :bordered="false" class="calculator-card">
    <a-form layout="vertical">
      <!-- 四售价输入 -->
      <a-row :gutter="16">
        <a-col :span="6" v-for="n in 4" :key="n">
          <a-form-item :label="`售价${n}（元）`" required>
            <a-input-number
                v-model:value="form.sellingPrices[n-1]"
                :min="0"
                :precision="2"
                :formatter="value => `¥ ${value}`"
                :parser="value => value.replace(/¥\s?/g, '')"
                style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 优惠券和折扣 -->
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="优惠券总金额（元）">
            <a-input-number
                v-model:value="form.couponValue"
                :min="0"
                :precision="2"
                style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="折扣率" required>
            <a-input-number
                v-model:value="form.discountRate"
                :min="0.01"
                :max="1"
                :step="0.01"
                :formatter="value => `${(value * 100).toFixed(0)}%`"
                :parser="value => value.replace('%','')/100"
                style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <!-- 计算结果 -->
    <a-divider />
    <a-table
        :dataSource="priceList"
        :columns="columns"
        :pagination="false"
        bordered
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'originalPrice'">
          {{ calculateOriginalPrice(record.sellingPrice) }}
        </template>
      </template>
    </a-table>
  </a-card>
</template>

<script setup>
import { reactive, computed } from 'vue';

// 响应式数据配置
const form = reactive({
  sellingPrices: [9.9, 19.8, 29.7, 49.5, 59.4], // 四售价初始值
  couponValue: 5,
  discountRate: 0.8
});

// 计算逻辑（基于定价公式：定价 = (售价 + 优惠券) / 折扣率）[1,2](@ref)
const calculateOriginalPrice = (sellingPrice) => {
  if(form.discountRate <= 0) return '无效折扣';
  return ((sellingPrice + form.couponValue) / form.discountRate).toFixed(2);
};

// 表格数据配置
const priceList = computed(() =>
    form.sellingPrices.map((price, index) => ({
      key: index,
      sellingPrice: price,
      label: `售价${index + 1}`
    }))
);

// 表格列配置
const columns = [
  { title: '销售价格', dataIndex: 'label' },
  { title: '对应定价（元）', dataIndex: 'originalPrice', align: 'right' }
];
</script>

<style scoped>
.calculator-card {
  max-width: 800px;
  margin: 20px auto;
  box-shadow: 0 3px 6px rgba(0,0,0,0.1);
}

:deep(.ant-table-cell) {
  font-weight: 500;
}
</style>